# -*- coding: utf-8 -*-
import datetime
from home.model import User_Info
from home.utils.array_utils import ListTools
from home.utils.string_utils import StringUtils

"""
用户信息管理服务类
"""


class User_Info_Service:
	
	def save_user(self, user):
		"""
		保存用户信息到数据库：新增或者更新
		:param user:
		:return:
		"""
		default_password = "0000000000"
		if user is None:
			return False
		if StringUtils.isEmpty(user.id):
			user.set_new_id()
		
		# filter返回一个列表
		entities = User_Info.objects.filter(id=user.id)
		if ListTools.isNotEmpty(entities):
			entity = entities[0]
			# 用户信息已经存在
			entity.name = user.name
			entity.email = user.email
			entity.nick_name = user.nick_name
			# 密码单独设置
			# user.user_pwd = user.user_pwd
			entity.is_admin = user.is_admin
			entity.article_count = user.article_count
			entity.create_time = user.create_time
			entity.update_time = datetime.datetime.now()
			entity.save()
		else:
			# 用户信息不存在
			user.is_admin = False
			user.article_count = 0
			user.create_time = datetime.datetime.now()
			user.update_time = datetime.datetime.now()
			User_Info.objects.create(id=user.id, name=user.name, email=user.email, nick_name=user.nick_name,
			                         user_pwd=default_password, is_admin=user.is_admin,
			                         article_count=user.article_count, create_time=user.create_time,
			                         update_time=user.update_time)
	
	def delete_user(self, id):
		"""
		根据ID删除指定的用户信息
		:param id:
		:return:
		"""
		if StringUtils.isEmpty(id):
			return False
		# 根据ID删除数据
		User_Info.objects.filter(id=id).delete()
		return True
	
	def filter_with_condition(self, **kwargs):
		"""
		根据email和pwd查询匹配的用户信息
		:param email:
		:param pwd:
		:return:
		"""
		args = []
		return User_Info.objects.filter(*args, **kwargs)
	
	def get_with_id(self, id):
		"""
		根据ID查询指定的用户信息
		:param email:
		:param pwd:
		:return:
		"""
		users = User_Info.objects.filter(id=id)
		if ListTools.isNotEmpty(users):
			return users[0]
		return None
